package com.laxcen.smoke.service.impl;

import com.laxcen.smoke.config.CommonEnum;
import com.laxcen.smoke.dao.AdvertisementDao;
import com.laxcen.smoke.dto.res.AdvertisementAndNoRes;
import com.laxcen.smoke.service.AdvertisementService;
import com.laxcen.smoke.util.DBUtils;
import com.laxcen.smoke.util.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

//import sun.misc.BASE64Decoder;

@Service
public class AdvertisementServiceImpl implements AdvertisementService {

    @Autowired
    private AdvertisementDao advertisementDao;



    @Value("${productkey}")
    private String ProductKey;

    @Value("${accessKey}")
    private String accessKey;

    @Value("${accessSecret}")
    private String accessSecret;

    @Value("${serviceip}")
    private String serviceip;

    @Override
    public Response insert(String adverimg) {
//        String realsmartid = advertisementDao.getSmartId(smartno);
//        if (realsmartid==null){
//            return new Response(CommonEnum.ZHINENGKUI_NOT_EXIST);
//        }
//        Advertisement advertisement = advertisementDao.getAdverBySmId(realsmartid);
//        if (advertisement!=null){
//            return new Response(CommonEnum.ADVERTISEMENT_IS_EXIST);
//        }

        //处理上传过来的图片流
//        String realadv = adverimg.replaceAll("data:image/jpg;","data:image/jpeg;");
        String dataPrix = ""; //base64格式前头
        String data = "";//实体部分数据
        StringBuilder sf = new StringBuilder();
        if (adverimg == null || "".equals(adverimg)) {
            return new Response(CommonEnum.IMAGE_IS_NULL);
        } else {
            String[] d = adverimg.split("base64,");//将字符串分成数组
            for (int i = 0; i < d.length; i++) {
                if (i==0){
                    dataPrix = d[0];
                    data = null;
                }
                if (d != null && i!=0) {
                    dataPrix = d[0];
                    data = d[0+i];
                    String suffix = "";//图片后缀，用以识别哪种格式数据
                    //编码的jpeg图片数据
                    if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)) {
                        suffix = ".jpeg";
                    } else if ("data:image/jpg;".equalsIgnoreCase(dataPrix)) {
                        //编码的jpg图片数据
                        suffix = ".jpg";
                    } else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {
                        //编码的gif图片数据
                        suffix = ".gif";
                    } else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {
                        //编码的png图片数据
                        suffix = ".png";
                    } else if ("data:image/bmp;".equalsIgnoreCase(dataPrix)) {
                        //
                        suffix = ".bmp";
                    } else {
                        return new Response(CommonEnum.IMAGE_WRONG);
                    }
//                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    BASE64Decoder decoder = new BASE64Decoder();
                    try {
                        //Base64解码
//                        String realdate = data.replace(","+dataPrix,"");
//                        byte[] b = Base64.getMimeDecoder().decode(realdate);
                        byte[] b = decoder.decodeBuffer(data);
                        //接收前端传过来的图片服务器相对路径
                        String filePath = "shiro-core/src/main/resources/webapp/adverimg/";
                        File validateCodeFolder = new File(filePath);
                    if (!validateCodeFolder.exists()) {
                        validateCodeFolder.mkdirs();
                        }
                    // 将字符串转换成二进制，用于显示图片
                    // 将上面生成的图片格式字符串 imgStr，还原成图片显示
//                    String type = ".jpg";
                    long sid = DBUtils.nextId();
                    String ssid = String.valueOf(sid) ;
                    String filename = ssid + suffix;
                    String realfilename = "http://"+serviceip+":8080/adverimg/"+filename;
                    InputStream in = new ByteArrayInputStream(b);
                    File file = new File(filePath, filename);// 可以是任何图片格式.jpg,.png等
                    FileOutputStream fos = new FileOutputStream(file);
                    byte[] bbs = new byte[1024];
                    int nRead = 0;
                    while ((nRead = in.read(bbs)) != -1) {
                    fos.write(bbs, 0, nRead);
                    }
                        fos.flush();
                        fos.close();
                        in.close();
                        if ("".equals(sf.toString())||sf.toString() == null){
                            sf.append(realfilename);
                        }else{
                            sf.append("," + realfilename);
                        }
                        if (i==d.length-1) {
                            long advids = DBUtils.nextId();
                            String advid  = String.valueOf(advids);
                            Date date = new Date();
                            //添加到advertisement表
                            advertisementDao.insertAdv(advid,sf.toString(),date,date);
//                            String[] sfarray = sf.toString().split(",");
//                            ArrayList arrayList = new ArrayList();
//                            for (int j = 0 ; j < sfarray.length;j++){
//                                arrayList.add(j,"\""+sfarray[j]+"\"");
//                            }
//                            System.out.println("Arraylist="+arrayList);
                            //添加到real_smart_advertisement表
//                            long radvids = DBUtils.nextId();
//                            String radvid  = String.valueOf(radvids);
//                            advertisementDao.insertRealAdv(radvid, IdUtils.getZandS(),advid,realsmartid,date);

                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else if (!adverimg.startsWith("data:")){
                    return new Response(CommonEnum.IMAGE_WRONG);
                }

            }
        }


        Response response = new Response();
        response.setOK();
        return response;
    }

    @Override
    public Response delete(String id) {
        advertisementDao.deleteRealAdv(id);
        Response response = new Response();
        response.setOK();
        return response;
    }

    @Override
    public Response update(String adverimg,String id) {
//        String realsmartid = advertisementDao.getSmartId(smartno);
//        if (realsmartid==null){
//            return new Response(CommonEnum.ZHINENGKUI_NOT_EXIST);
//        }
//        Advertisement advertisement = advertisementDao.getAdverBySmId(realsmartid);
//        if (advertisement!=null){
//            return new Response(CommonEnum.ADVERTISEMENT_IS_EXIST);
//        }
        //处理上传过来的图片流
//        String realadv = adverimg.replaceAll("data:image/jpg;","data:image/jpeg;");
        String dataPrix = ""; //base64格式前头
        String data = "";//实体部分数据
        StringBuilder sf = new StringBuilder();
        if (adverimg == null || "".equals(adverimg)) {
            return new Response(CommonEnum.IMAGE_IS_NULL);
        } else {
            String[] d = adverimg.split("base64,");//将字符串分成数组
            for (int i = 0; i < d.length; i++) {
                if (i==0){
                    dataPrix = d[0];
                    data = null;
                }
                if (d != null && i!=0) {
                    dataPrix = d[0];
                    data = d[0+i];
                    String suffix = "";//图片后缀，用以识别哪种格式数据
                    //编码的jpeg图片数据
                    if ("data:image/jpeg;".equalsIgnoreCase(dataPrix)) {
                        suffix = ".jpeg";
                    } else if ("data:image/jpg;".equalsIgnoreCase(dataPrix)) {
                        //编码的jpg图片数据
                        suffix = ".jpg";
                    } else if ("data:image/gif;".equalsIgnoreCase(dataPrix)) {
                        //编码的gif图片数据
                        suffix = ".gif";
                    } else if ("data:image/png;".equalsIgnoreCase(dataPrix)) {
                        //编码的png图片数据
                        suffix = ".png";
                    } else if ("data:image/bmp;".equalsIgnoreCase(dataPrix)) {
                        //
                        suffix = ".bmp";
                    }
//                    else {
//                        return new Response(CommonEnum.IMAGE_WRONG);
//                    }
//                    String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                    BASE64Decoder decoder = new BASE64Decoder();
                    try {
                        //Base64解码
//                        String realdate = data.replace(","+dataPrix,"");
                        byte[] b = decoder.decodeBuffer(data);
                        String filePath = "shiro-core/src/main/resources/webapp/adverimg/";
                        File validateCodeFolder = new File(filePath);
                        if (!validateCodeFolder.exists()) {
                            validateCodeFolder.mkdirs();
                        }
                        // 将字符串转换成二进制，用于显示图片
                        // 将上面生成的图片格式字符串 imgStr，还原成图片显示
//                        String type = ".jpg";
                        long sid = DBUtils.nextId();
                        String ssid = String.valueOf(sid) ;
                        String filename = ssid + suffix;
                        String realfilename = "http://"+serviceip+":8080/adverimg/"+filename;
                        InputStream in = new ByteArrayInputStream(b);
                        File file = new File(filePath, filename);// 可以是任何图片格式.jpg,.png等
                        FileOutputStream fos = new FileOutputStream(file);
                        byte[] bbs = new byte[1024];
                        int nRead = 0;
                        while ((nRead = in.read(bbs)) != -1) {
                            fos.write(bbs, 0, nRead);
                        }
                        fos.flush();
                        fos.close();
                        in.close();
                        if ("".equals(sf.toString())||sf.toString() == null){
                            sf.append(realfilename);
                        }else{
                            sf.append("," + realfilename);
                        }
                        if (i==d.length-1) {
                            String[] sfarray = sf.toString().split(",");
                            ArrayList arrayList = new ArrayList();
                            for (int j = 0 ; j < sfarray.length;j++){
                                arrayList.add(j,"\""+sfarray[j]+"\"");
                            }
                            advertisementDao.updateAdv(sf.toString(),new Date(),id);
//                            advertisementDao.updateAdvReal(realsmartid,id);
                            //服务下发到iot
//                            IClientProfile profile = DefaultProfile.getProfile("cn-shanghai", accessKey, accessSecret);
//                            DefaultAcsClient client = new DefaultAcsClient(profile);
//                            InvokeThingServiceRequest request = new InvokeThingServiceRequest();
//                            String param = "{\"Url\":"+arrayList+"}";
////                            System.out.println("param="+param);
//                            request.setArgs(param);
//                            request.setIdentifier("Advertisement");
//                            request.setProductKey(ProductKey);
//                            request.setDeviceName(devicename);
//                            try
//                            {
//                                InvokeThingServiceResponse response = client.getAcsResponse(request);
//                            }
//                            catch (ServerException e)
//                            {
//                                e.printStackTrace();
//                            }
//                            catch (ClientException e)
//                            {
//                                e.printStackTrace();
//                            }
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
//                else if (!adverimg.startsWith("data:")){
//                    return new Response(CommonEnum.IMAGE_WRONG);
//                }

            }
        }


        Response response = new Response();
        response.setOK();
        return response;
    }

    @Override
    public Response<List<AdvertisementAndNoRes>> getList() {

        List<AdvertisementAndNoRes> list = advertisementDao.getAdvList();
        Response<List<AdvertisementAndNoRes>> response = new Response<>();
        response.setOK();
        response.setData(list);
        return response;
    }

    @Override
    public Response<List<AdvertisementAndNoRes>> getListByCondition(String starttime,String endtime) throws ParseException {
        List<AdvertisementAndNoRes> list = new LinkedList<>();
        if ("".equals(starttime)&&"".equals(endtime)){
            list = advertisementDao.getAdvList();
        }else if(!"".equals(starttime)&&!"".equals(endtime)){
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss") ;
            Date datestart = sdf.parse(starttime);
            Date dateend = sdf.parse(endtime);
            list = advertisementDao.getAdvListByCreatetime(datestart, dateend);
        }else if (starttime==null&&endtime==null) {
            list = advertisementDao.getAdvList();
        }else if(starttime!=null&&endtime!=null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date datestart = sdf.parse(starttime);
            Date dateend = sdf.parse(endtime);
            list = advertisementDao.getAdvListByCreatetime(datestart, dateend);
        }
        Response<List<AdvertisementAndNoRes>> response = new Response<>();
        response.setOK();
        response.setData(list);
        return response;
    }

    @Override
    public Response<AdvertisementAndNoRes> getOneAdv(String id) {
        AdvertisementAndNoRes advertisement = advertisementDao.getOneAdv(id);
        Response<AdvertisementAndNoRes> response = new Response<>();
        response.setData(advertisement);
        response.setOK();
        return response;
    }
}
